import { unref, watch } from 'vue';
import { useMutationObserver } from './useMutationObserver';
import { isFunction, isString, resolveRef } from './shared';

// 将title变成一个响应式的
export function useTitle(newTitle = null, options = {}) {
  const { document = window.document } = options;
  // 创建一个响应式的title computed 或 ref
  const title = resolveRef(newTitle || document.title);

  // 如果是一个function 则转换成computed 所以不允许修改
  const isReadonly = newTitle && isFunction(newTitle);

  // '%s | 我的标题' => `${title} | 我的标题`
  function format(t) {
    if (!('titleTemplate' in options)) return t;
    const template = options.titleTemplate || '%s';
    return isFunction(template)
      ? template(t)
      : unref(template).replace(/%s/g, t);
  }

  // title 变化时更新 title
  watch(
    title,
    (t, o) => {
      if (t !== o && document) document.title = format(isString(t) ? t : '');
    },
    { immediate: true }
  );

  if (options.observe && !options.titleTemplate && document && !isReadonly) {
    useMutationObserver(
      document.head.querySelector('title'),
      () => {
        console.log('title changed!');
        if (document && document.title !== title.value) title.value = format(document.title);
      },
      { childList: true }
    );
  }

  return title;
}
